<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button class="btn">发消息</button>
  <button class="btn2">关闭连接</button>
  <script>
    // 创建链接
    const ws = new WebSocket('wss://javascript.info/article/websocket/demo/hello')
    // 连接成功
    ws.onopen = () => {
      console.log('连接成功了');
    }

    // 发消息
    document.querySelector('.btn').addEventListener('click', () => {
      ws.send('你好服务器')
    })

    // 收消息
    ws.onmessage = event => {
      console.log('event', event)
    }

    
    // 监听关闭连接
    ws.onclose = event => {
      console.log('关闭连接')
    }
    // 关闭连接
    document.querySelector('.btn2').addEventListener('click', () => {
      ws.close()
    })

  </script>
</body>

</html>